<!--
 * @Descripttion: 聊天内容
 * @Author: 银河以北
 * @Date: 2021-09-22 22:15:09
 * @LastEditors: 银河以北
 * @LastEditTime: 2021-10-07 13:57:28
-->
<template>
  <div class='chat'>
    <!-- 标题 -->
    <div class='chat-title'>
      <div>
        <h3>{{sendNickname}}</h3>
      </div>
      <div
        class='group-chat'
        v-if="!isChat"
      >
        <div>
          <el-popover
            placement="left"
            :width="400"
            trigger="click"
          >
            <template #reference>
              <el-icon
                :size='20'
                class='group-chat-setting'
                style="margin-top:10px;margin-right:5px"
                @click="getGroupChatInfos"
              >
                <Setting />
              </el-icon>
            </template>
            <div class='group-chat-info'>
              <GroupChatInfo
                :groupInfo='groupInfo'
                @updateGroupList='updateGroupList'
              ></GroupChatInfo>
            </div>
          </el-popover>
        </div>

      </div>
    </div>
    <!-- 分割线 -->
    <div class='divider'></div>
    <!-- 聊天内容 -->
    <div
      class='chat-container'
      ref='chatContainer'
    >
      <div
        class='chat-more'
        v-if="isShowMore"
      >
        <div @click="getMoreChatMsg">加载更多</div>
      </div>
      <div
        class='chat-container-item'
        :class='{"chat-container-star":item.user_id!=userInfo?.id,"chat-container-end":item.user_id==userInfo?.id}'
        v-for='(item,index) in msgList'
        :key='index'
      >
        <div>
          <div>
            <div
              v-if='item.user_id==userInfo?.id'
              style="width:70px"
            >
              <el-avatar
                :size="50"
                :src="$utils.imgUrl(item.getUserInfo.avatar_url)"
              ></el-avatar>
            </div>
            <div
              v-else
              style="width:70px"
            >
              <el-avatar
                :size="50"
                :src="$utils.imgUrl(item.getUserInfo.avatar_url)"
              ></el-avatar>
            </div>
          </div>
          <div style="display:block">
            <p class='user-name'><span style="margin-right:10px">{{item.getUserInfo.nickname}}</span> <span>{{item.create_time.substring(0,16)}}</span></p>
            <p class='user-contont'><span v-html="item.content"></span></p>
          </div>
        </div>
      </div>
    </div>
    <!-- 分割线 -->
    <div class='divider'></div>
    <!-- 文本域 -->
    <div class='chat-send'>
      <!-- 发送文本域 -->
      <textarea
        class='chat-send-textarea'
        v-model="textarea"
        @keyup.enter="sendMsg"
      ></textarea>
      <!-- 发送图标 -->
      <div class='chat-send-icon'>
        <el-icon
          :size='30'
          color='#409EFF'
          @click="sendMsg"
        >
          <Promotion />
        </el-icon>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import {
  computed,
  defineComponent,
  reactive,
  ref,
  watch,
  nextTick,
  toRefs,
} from "vue";
import base from "@/config/defaultSettings";
import { getStandardTime } from "@/utils/utils";

import {
  getChatContentList,
  sendGroupChatContent,
  getGroupChatMsgList,
  getGroupChatInfo,
} from "@/api/chat/index";
//svg-icon
import { Promotion, Setting } from "@element-plus/icons";
import GroupChatInfo from "./groupChatInfo.vue";

//vuex
import { useStore } from "vuex";
export default defineComponent({
  name: "ChatContainer",
  components: {
    Promotion,
    Setting,
    GroupChatInfo,
  },
  props: {
    activeChatItem: {
      type: Object,
      default: () => {},
    },
  },
  setup(props, { emit }) {
    //创建长链接对象
    const SOCKET = new WebSocket(base.websocketUrl);

    //引入vuex
    const store = useStore();

    //聊天消息
    const msgList: any = reactive([]);

    const sendNickname = ref<string>("未知用户");

    //返回用户信息
    const userInfo: any = computed(() => {
      return store.getters.userInfo;
    });

    //分页参数
    const pagesParams = reactive({
      page: 1,
      list_rows: 20,
      total: 0,
    });

    //是否显示更多按钮
    let isShowMore = ref<boolean>(false);

    //监听用户信息
    watch(userInfo, (value) => {
      // console.log(value, "xxx");
    });

    //判断是群聊 还是 一对一 聊天
    let isChat = ref<boolean>(true);

    //监听活动的聊天实例
    watch(props.activeChatItem, (value) => {
      //分页参数重置
      pagesParams.page = 1;
      pagesParams.list_rows = 20;
      pagesParams.total = 0;

      //根据不同的聊天类型来请求对应的数据
      if (value.type == "chat") {
        isChat.value = true;
        if (value.id != 0) {
          const data = {
            user_id: value.user_id,
            send_id: value.send_id,
            ...pagesParams,
          };
          sendNickname.value = props.activeChatItem.send_nickname;
          getChatContentList(data).then((res) => {
            msgList.length = 0;
            msgList.push(...res.data.data.reverse());
            pagesParams.total = res.data.total;

            //判断显示更多是否需要展示
            if (pagesParams.page * pagesParams.list_rows < pagesParams.total) {
              isShowMore.value = true;
            } else {
              isShowMore.value = false;
            }
            emit("changeNotRead", props.activeChatItem.send_id);
            nextTick(() => {
              chatContainer.value.scrollTop = chatContainer.value.scrollHeight;
            });
          });
        }
      } else {
        let data = { groupId: props.activeChatItem.id };
        data = Object.assign({}, data, pagesParams);
        getGroupChatMsgList(data).then((res) => {
          msgList.length = 0;
          msgList.push(...res.data.data.reverse());
          pagesParams.total = res.data.total;
          //判断显示更多是否需要展示
          if (pagesParams.page * pagesParams.list_rows < pagesParams.total) {
            isShowMore.value = true;
          } else {
            isShowMore.value = false;
          }
          nextTick(() => {
            chatContainer.value.scrollTop = chatContainer.value.scrollHeight;
          });
        });
        isChat.value = false;
        sendNickname.value = value.send_nickname;
      }
    });

    //连接成功，绑定用户ID
    // SOCKET.onopen = () => {
    //   // const data = {
    //   //   userId: `${base.chatTag}${userInfo.value.id}`,
    //   //   type: "chatBind",
    //   //   content: "初次连接",
    //   // };
    //   // SOCKET.send(JSON.stringify(data));
    // };

    //长链接接收消息
    SOCKET.onmessage = (data) => {
      const info = JSON.parse(data.data);
      /* 获取设备ID */
      if (info.type == "client_id") {
        //vuex存储设备ID
        store.commit("SET_ClientID", info.client_id);
        bindUserId();
      }

      /* 群聊消息 */
      if (info.type == "groupChat") {
        if (props.activeChatItem.id == info.group_id) {
          info.create_time = getStandardTime();
          msgList.push(info);
          nextTick(() => {
            chatContainer.value.scrollTop = chatContainer.value.scrollHeight;
          });
        }
      }

      /* 一对一聊天 */
      if (info.type == "chat") {
        if (
          info.send_id == `${base.chatTag}${userInfo.value.id}` &&
          info.user_id == `${base.chatTag}${props.activeChatItem.send_id}`
        ) {
          //添加进消息队列
          msgList.push(info);
          nextTick(() => {
            chatContainer.value.scrollTop = chatContainer.value.scrollHeight;
          });
        } else {
          emit("addNotRead", info);
        }
      }
    };

    //绑定用户ID 在获取设备ID之后
    const bindUserId = () => {
      const data = {
        userId: `${base.chatTag}${userInfo.value.id}`,
        type: "chatBind",
        content: "初次连接",
        client_id: store.getters.getSocketClientId,
      };
      SOCKET.send(JSON.stringify(data));
    };

    //连接失败
    SOCKET.onerror = (e) => {
      console.log("连接失败", e);
    };

    const chatContainer = ref<any>(null);
    //发送消息
    const sendMsg = () => {
      if (props.activeChatItem.type == "chat") {
        const data = {
          type: "chat",
          user_id: userInfo.value.id,
          send_id: props.activeChatItem.send_id,
          content: textarea.value,
          create_time: getStandardTime(),
          getUserInfo: {
            nickname: userInfo.value.nickname,
            avatar_url: userInfo.value.avatar_url,
            id: userInfo.value.id,
          },
        };
        msgList.push(data);
        const sendData = Object.assign({}, data);
        const sendId = `${base.chatTag}${props.activeChatItem.send_id}`;
        sendData.send_id = sendId;
        sendData.user_id = `${base.chatTag}${sendData.user_id}`;
        SOCKET.send(JSON.stringify(sendData));
        textarea.value = "";
        nextTick(() => {
          chatContainer.value.scrollTop = chatContainer.value.scrollHeight;
        });
      } else {
        const data = {
          group_id: props.activeChatItem.id,
          content: textarea.value,
          groupId: store.getters.getSocketClientId,
        };
        sendGroupChatContent(data);
        textarea.value = "";
      }
    };

    //获取跟多信息
    const getMoreChatMsg = () => {
      pagesParams.page++;
      if (props.activeChatItem.type == "chat") {
        const data = {
          user_id: props.activeChatItem.user_id,
          send_id: props.activeChatItem.send_id,
          ...pagesParams,
        };

        getChatContentList(data).then((res) => {
          msgList.unshift(...res.data.data.reverse());
          //判断显示更多是否需要展示
          if (pagesParams.page * pagesParams.list_rows < pagesParams.total) {
            isShowMore.value = true;
          } else {
            isShowMore.value = false;
          }
        });
      }
      if (props.activeChatItem.type == "groupChat") {
        let data = { groupId: props.activeChatItem.id };
        data = Object.assign({}, data, pagesParams);
        getGroupChatMsgList(data).then((res) => {
          msgList.unshift(...res.data.data.reverse());
          if (pagesParams.page * pagesParams.list_rows < pagesParams.total) {
            isShowMore.value = true;
          } else {
            isShowMore.value = false;
          }
        });
      }
    };

    //群组信息
    let datas = reactive({
      groupInfo: {},
    });

    //获取群组信息
    const getGroupChatInfos = () => {
      const data = {
        groupId: props.activeChatItem.id,
      };
      getGroupChatInfo(data).then((res) => {
        datas.groupInfo = res.data;
        // console.log(groupInfo, "xx");
      });
    };

    //更新群组信息
    const updateGroupList = () => {
      emit("updateGroupList");
    };

    //输入框变量
    let textarea = ref("");
    return {
      textarea, //输入框变量

      sendMsg, //发送消息

      msgList, //消息列表

      userInfo, //用户信息

      chatContainer, //聊天框DIV

      sendNickname, //聊天对象用户名

      bindUserId, //绑定用户ID 在获取设备ID之后

      isChat, //判断是群聊还是一对一 单聊

      pagesParams, //分页参数

      isShowMore, //是否显示更多

      getMoreChatMsg, //获取更多信息

      getGroupChatInfos, //获取群组信息

      // groupInfo, //群组信息
      ...toRefs(datas),

      updateGroupList, //更新群聊信息
    };
  },
});
</script>

<style lang="scss" scoped>
@import "@/style/common/defaultStyle";
.chat {
  width: 830px;
  height: 100%;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  background: #f5f5f5;
  &-title {
    width: 100%;
    height: 40px;
    display: flex;
    justify-content: space-between;
    h3 {
      line-height: 40px;
      margin-left: 20px;
    }
    .group-chat {
      display: flex;
      justify-content: center;
      align-content: center;
      cursor: pointer;

      .group-chat-info {
        width: 100%;
      }
      .group-chat-setting {
        transition: 1s;
      }
      .group-chat-setting:hover {
        transform: rotate(360deg);
        color: #52adff;
      }
    }
  }
  .divider {
    width: 100%;
    height: 1px;
    background: #e7e7e7;
  }
  &-container {
    width: 100%;
    height: 400px;
    .chat-more {
      top: 50px;
      z-index: 100;
      right: 50%;
      display: flex;
      justify-content: center;
      margin: 5px;
      div {
        padding: 5px;
        background: #fff;
        font-size: 12px;
        border-radius: 5px;
        overflow: hidden;
        cursor: pointer;
      }
    }

    //混入公共滚动条
    @include scrollBarStyle;
    &-item {
      width: calc(100% - 20px);
      padding: 10px;
      display: flex;
      div {
        max-width: 70%;
      }
    }
    &-star {
      justify-content: flex-start;
      div {
        display: flex;
      }
    }
    &-end {
      justify-content: flex-end;
      div {
        display: flex;
        flex-direction: row-reverse;
      }
    }
    .user-name {
      max-width: 300px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      color: #a5b5c1;
      font-size: 12px;
      margin-bottom: 5px;
    }
    .user-contont {
      background: #5cadff;
      padding: 5px;
      color: #fff;
      border-radius: 5px;
      font-size: 14px;
    }
  }
  &-send {
    width: 100%;
    height: 108px;
    position: relative;
    &-textarea {
      width: calc(100% - 20px);
      height: calc(100% - 20px);
      outline: none;
      border: none;
      padding: 10px;
      resize: none;
    }
    &-icon {
      cursor: pointer;
      position: absolute;
      right: 5px;
      bottom: 5px;
    }
  }
}
</style>